import { Select } from "antd";
import React from "react";
import { Row } from "types";

const toNumber = (val: unknown) => {
  if (isNaN(Number(val))) {
    return 0;
  }

  return Number(val);
};

interface Iprops
  extends Omit<
    React.ComponentProps<typeof Select>,
    "value" | "onChange" | "options"
  > {
  value?: Row | null | undefined;
  onChange?: (value?: number) => void;
  defaultOptionName?: string;
  options?: { name: string; id: number }[];
}

/**
 * value 可以传入多种类型的值
 * onChange只会回调 number | undefined 类型
 * 当isNaN(Number(value)) 为true的时候，代表选择默认类型
 * 当选择默认类型的时候，onChange会回调undefined
 * @param param0
 * @returns
 */
const IdSelect: React.FC<Iprops> = ({
  value,
  onChange,
  defaultOptionName,
  options,
  ...resetProps
}) => {
  return (
    <Select
      value={options?.length ? toNumber(value) : 0}
      onChange={(val) => onChange?.(toNumber(val) || undefined)}
      {...resetProps}
    >
      {defaultOptionName && (
        <Select.Option value={0}>{defaultOptionName}</Select.Option>
      )}
      {options?.length &&
        options.map(({ name, id }, index) => {
          return (
            <Select.Option value={id} key={`${id}_${index}`}>
              {name}
            </Select.Option>
          );
        })}
    </Select>
  );
};

export default IdSelect;
